﻿using System;
using System.Collections.Generic;
using System.Text;
using ZhongJia.Core.Tcp;
using ZhongJia.Lock.Infrastructure.Extensions;

namespace ZhongJia.Lock.Core.Models
{
    public class TcpPackage : PacketBase
    {
        private byte[] _data;

        public TcpPackage(byte[] data)
        {
            _data = data;
        }

        public TcpPackage(ByteBuilder byteBuilder)
        {
            _data = byteBuilder.ToArrayThenClear();
            var  totalLength = _data[1];
            if (_data.Length < totalLength + 1)
                return;
            if (_data.Length > totalLength + 1)
            {
                var temp = new byte[totalLength + 1];
                Array.Copy(_data, 0, temp, 0, totalLength + 1);
                _data = temp;
            }
            Command = (TcpCommand)_data[2];
        }

        public TcpCommand Command { get; set; }

        public override byte[] ToByteArray()
        {
            return _data;
        }

        public static TcpPackage GetPacket(ByteBuilder builder)
        {
            if (builder.Length == 0)
                return null;

            return new TcpPackage(builder);
        }

        public static TcpPackage BuildPacket(int totalLength, TcpCommand command, string serialNumber = "")
        {
            byte[] bytes = new byte[totalLength + 1];
            return new TcpPackage(bytes);
        }

        public string GetLockSerialNumber()
        {
            return $"{_data[3] * 256 + _data[4]}-{_data[5]}-{_data[6]}"; 
        }

        public override string ToString()
        {
            return $"数据包：{ _data.BytesToHexString()}";
        }
    }
}
